package com.chookss.home.audit.reimbursement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.AuditActivity;
import com.chookss.home.audit.MyAuditRecordActivity;
import com.chookss.home.audit.service.UploadReimbursementService;
import com.chookss.home.audit.clockIn.ClockInUtils;
import com.chookss.home.audit.adapter.FilesAdapter;
import com.chookss.home.audit.adapter.ShopChoiceAdapter;
import com.chookss.home.audit.shop.ShopChoiceActivity;
import com.chookss.home.audit.shop.ShopNormalActivity;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.home.entity.ReimbursementTypeEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.ShopEvent;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DrawableTextView;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.LogBottomDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReimbursementActivity extends BaseAct {
//报销首页 借款首页  补贴首页

    @BindView(R.id.tvType)
    DrawableTextView tvType;
    @BindView(R.id.llType)
    LinearLayout llType;
    @BindView(R.id.llCode)
    LinearLayout llCode;
    @BindView(R.id.llDepartent)
    LinearLayout llDepartent;
    @BindView(R.id.tvCode)
    TextView tvCode;
    @BindView(R.id.emptyDepartment)
    View emptyDepartment;

    @BindView(R.id.tvGroup)
    DrawableTextView tvGroup;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.edMoney)
    EditText edMoney;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llGroup)
    LinearLayout llGroup;
    @BindView(R.id.groupEmpty)
    View groupEmpty;
    @BindView(R.id.ivAudit)
    ImageView ivAudit;
    @BindView(R.id.tvTypeInit)
    TextView tvTypeInit;
    @BindView(R.id.edMoneyInit)
    TextView edMoneyInit;
    @BindView(R.id.edContentInit)
    TextView edContentInit;
    @BindView(R.id.tvShopInit)
    TextView tvShopInit;
    @BindView(R.id.emptyShop)
    View emptyShop;
    @BindView(R.id.llShop)
    LinearLayout llShop;
    @BindView(R.id.borrowEmpty)
    View borrowEmpty;
    @BindView(R.id.llBorrow)
    LinearLayout llBorrow;
    @BindView(R.id.tvBorrow)
    DrawableTextView tvBorrow;
    @BindView(R.id.shopRcv)
    RecyclerView shopRcv;
    @BindView(R.id.reimbursementRcv)
    RecyclerView reimbursementRcv;
    @BindView(R.id.tvTypeRemark)
    TextView tvTypeRemark;
    private static final int REQUEST_CODE_CHOOSE = 23;
    private ReimbursementDetailEntity reimbursementDetailEntity = null;
    private List<ReimbursementTypeEntity> reimbursementTypeEntities = new ArrayList<>();
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    private List<ReimbursementDetailEntity.AnnexsBean> filesList = new ArrayList<>();
    private List<ReimbursementDetailEntity.AnnexsBean> reimbursementList = new ArrayList<>();
    private FilesAdapter adapter, reimbursementAdapter;
    private String[] groupArray = null;
    private String[] reimbursementArray = null;
    private String baoxiaoCode = "", workflowId = "";//不为空说明是修改进来的
    private String groupCode = "", groupName = "", reimbursementTypeCode = "";
    private boolean errorStatus = false;//true 说明是上传失败进来
    private String tag = "ReimbursementActivity_DownloadFile";//下载文件打的标签
    private String reimbursementTag = "ReimbursementActivity_reimbursement_DownloadFile";//下载文件打的标签
    private LogBottomDialog bottomDialog = null;
    private int type = 7;//
    private String orgCode = "", orgName = "";//所属部门
    private String remark = "";//借款说明
    private String goodsCode = "";//关联物品
    private String baoxiaoTypeName = "";//还款类型名称
    private ArrayList<ReimbursementDetailEntity.GoodsInfosBean> shopList = new ArrayList<>();
    private ArrayList<ReimbursementDetailEntity.GoodsInfosBean> threeList = new ArrayList<>();
    private ShopChoiceAdapter shopChoiceAdapter;
    private boolean isEditReimbursement = false;//还款修改标识
    private boolean reimbursement = false;//是否还款
    private int borrow_index = -1;//借款选中
    private WorkNewEntity borrowEntity = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reimbursement);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 7);
        isEditReimbursement = getIntent().getBooleanExtra("isEditReimbursement", false);
        reimbursement = getIntent().getBooleanExtra("reimbursement", false);
        baoxiaoCode = getIntent().getStringExtra("projectCode");
        workflowId = getIntent().getStringExtra("workflowId");
        errorStatus = getIntent().getBooleanExtra("errorStatus", false);
        KLog.i("isEditReimbursement==" + isEditReimbursement);
        KLog.i("reimbursement==" + reimbursement);
        if (type == 7) {
            //报销
            NavigationTools.saveUseRecord(this, "1", "30");
            borrowEmpty.setVisibility(View.VISIBLE);
            llBorrow.setVisibility(View.VISIBLE);
        } else if (type == 10) {
            //补贴
            NavigationTools.saveUseRecord(this, "1", "33");
            tvTitle.setText("补贴");
            tvTypeInit.setText("补贴类型");
            edMoneyInit.setText("补贴金额");
            edContentInit.setText("补贴事由");
        } else {
            NavigationTools.saveUseRecord(this, "1", "32");
            //借款
            edMoneyInit.setText("借款金额");
            if (reimbursement || isEditReimbursement) {
                tvTitle.setText(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + "的还款申请");
                edContentInit.setText("还款说明");
                llType.setVisibility(View.GONE);
                emptyDepartment.setVisibility(View.GONE);
                llDepartent.setVisibility(View.GONE);
                llCode.setVisibility(View.VISIBLE);
                emptyShop.setVisibility(View.VISIBLE);
                llShop.setVisibility(View.VISIBLE);
                shopRcv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                shopChoiceAdapter = new ShopChoiceAdapter(R.layout.item_shop_choice, this, threeList);
                ((SimpleItemAnimator) shopRcv.getItemAnimator()).setSupportsChangeAnimations(false);
                shopRcv.setAdapter(shopChoiceAdapter);
                reimbursementRcv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                reimbursementAdapter = new FilesAdapter(R.layout.item_files_list, this, reimbursementList, 0, reimbursementTag);
                ((SimpleItemAnimator) reimbursementRcv.getItemAnimator()).setSupportsChangeAnimations(false);
                reimbursementRcv.setAdapter(reimbursementAdapter);
                edMoney.setEnabled(false);
                edMoney.setClickable(false);
            } else {
                tvTitle.setText("借款");
                tvTypeInit.setText("借款类型");
                edContentInit.setText("借款事由");
            }

        }
        fileRcv.setLayoutManager(new LinearLayoutManager(this));
        if (reimbursement || isEditReimbursement) {
            //还款情况下 附件不可编辑
            adapter = new FilesAdapter(R.layout.item_files_list, this, filesList, 1, tag);
        } else {
            if (type == 7 || type == 10) {
                //报销  补贴
                tag = "ReimbursementActivity_normal_DownloadFile";
            }
            adapter = new FilesAdapter(R.layout.item_files_list, this, filesList, 0, tag);
        }
        fileRcv.setAdapter(adapter);
        orgCode = new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, "");
        orgName = new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, "");
        tvDepartment.setText(orgName);
        if (errorStatus) {
            //上传失败进来的
            reimbursementDetailEntity = (ReimbursementDetailEntity) getIntent().getSerializableExtra("data");
            if ("3".equals(reimbursementDetailEntity.getType()) || "4".equals(reimbursementDetailEntity.getType())) {
                //还款或者还款修改
                reimbursementRcv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                reimbursementAdapter = new FilesAdapter(R.layout.item_files_list, this, reimbursementList, 0, tag);
                ((SimpleItemAnimator) reimbursementRcv.getItemAnimator()).setSupportsChangeAnimations(false);
                reimbursementRcv.setAdapter(reimbursementAdapter);
            }
            tvSure.setText("重新提交");
            setErrorData();
        } else {
            reimbursementDetailEntity = new ReimbursementDetailEntity();
            List<ReimbursementDetailEntity.AnnexsBean> annexsBeanList = new ArrayList<>();
            reimbursementDetailEntity.setAnnexs(annexsBeanList);
            List<ReimbursementDetailEntity.AnnexsBean> annexsBeanList2 = new ArrayList<>();
            reimbursementDetailEntity.setRepaymentAnnexs(annexsBeanList2);
        }
        getGroupList();
        if (!reimbursement && !isEditReimbursement) {
            getReimbursementTypeList();
        }

        getworkList();
        if (!Utils.isNull(baoxiaoCode)) {
            selectDeail();
            if (!reimbursement) {
                //还款的不用这些
                tvSure.setText("重新提交");
                registerBoradcastReceiver();
            }
        }
    }

    private void setErrorData() {
        //上传失败后数据的初始化
        if (reimbursementDetailEntity != null) {
            reimbursementTypeCode = reimbursementDetailEntity.getBaoixaoTypeCode();
            tvType.setText(reimbursementDetailEntity.getBaoxiaoTypeName());
            edMoney.setText(reimbursementDetailEntity.getAmt());
            groupCode = reimbursementDetailEntity.getGroupCode();
            groupName = reimbursementDetailEntity.getGroupName();
            if (!Utils.isNull(reimbursementDetailEntity.getGroupCode())) {
                tvGroup.setText(reimbursementDetailEntity.getGroupName() + "(" + ClockInUtils.getGroupEnd(reimbursementDetailEntity.getGroupCode()) + ")");
                groupEmpty.setVisibility(View.VISIBLE);
                llGroup.setVisibility(View.VISIBLE);
            }
            if (!Utils.isNull(reimbursementDetailEntity.getOrgName())) {
                tvDepartment.setText(reimbursementDetailEntity.getOrgName());
                orgCode = reimbursementDetailEntity.getOrgCode();
                orgName = reimbursementDetailEntity.getOrgName();
            }
            if (Utils.isNull(reimbursementDetailEntity.getRemark())) {
                edContent.setText("无");
            } else {
                edContent.setText(reimbursementDetailEntity.getRemark());
            }
            filesList.clear();
            filesList.addAll(reimbursementDetailEntity.getAnnexs());
            adapter.notifyDataSetChanged();
            reimbursementList.clear();
            reimbursementList.addAll(reimbursementDetailEntity.getRepaymentAnnexs());
            reimbursementAdapter.notifyDataSetChanged();
            if (type == 9) {
                //借款还款
                if (reimbursementList.size() > 0) {
                    reimbursement = true;
                    reimbursementRcv.setVisibility(View.VISIBLE);
                }
            }
            getReimbursementNameList(true);
        }
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvType == null) {
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getReimbursementTypeList() {
        //获取报销类型列表
        Map<String, String> map = new HashMap<>();
        if (type == 7) {
            map.put("type", "1");//(1-报销 2-借款 3物品4请假5补贴
        } else if (type == 10) {
            map.put("type", "5");//(1-报销 2-借款 3物品4请假5补贴
        } else {
            map.put("type", "2");//(1-报销 2-借款 3物品4请假
        }
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<ReimbursementTypeEntity>>>() {
        }.getType(), null, Urls.selectBaoxiaoTypeList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ReimbursementTypeEntity>>() {
            @Override
            public void onSuccess(List<ReimbursementTypeEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvType == null) {
                        return;
                    }
                    reimbursementTypeEntities.clear();
                    reimbursementTypeEntities.addAll(data);
                    reimbursementArray = new String[reimbursementTypeEntities.size()];
                    for (int i = 0; i < reimbursementTypeEntities.size(); i++) {
                        reimbursementArray[i] = reimbursementTypeEntities.get(i).getBaoixaoTypeName();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getReimbursementNameList(boolean isEdit) {
        //获取报销名称列表
        Map<String, String> map = new HashMap<>();
        map.put("baoixaoTypeCode", reimbursementTypeCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<ReimbursementTypeEntity>>() {
        }.getType(), null, Urls.selectBaoxiaoInfDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementTypeEntity>() {
            @Override
            public void onSuccess(ReimbursementTypeEntity data) {
                if (tvType == null) {
                    return;
                }
                if (isEdit) {
                    //修改或者本地缓存数据 需要设置一下是否需要附件
                    if (reimbursement || isEditReimbursement) {
                        for (int i = 0; i < data.getRepaymentAnnexs().size(); i++) {
                            reimbursementList.get(i).setNeedCd(data.getRepaymentAnnexs().get(i).getNeedCd());
                        }
                    } else {
                        for (int i = 0; i < data.getAnnexs().size(); i++) {
                            filesList.get(i).setNeedCd(data.getAnnexs().get(i).getNeedCd());
                        }
                    }
                } else {
                    if (reimbursement || isEditReimbursement) {
                        reimbursementDetailEntity.getRepaymentAnnexs().clear();
                        reimbursementList.clear();
                        for (int i = 0; i < data.getRepaymentAnnexs().size(); i++) {
                            ReimbursementDetailEntity.AnnexsBean annexsBean = new ReimbursementDetailEntity.AnnexsBean();
                            annexsBean.setAnnexName(data.getRepaymentAnnexs().get(i).getAnnexName());
                            annexsBean.setBaoixaoTypeCode(reimbursementTypeCode);
                            annexsBean.setNeedCd(data.getRepaymentAnnexs().get(i).getNeedCd());
                            List<ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean> list = new ArrayList<>();
                            annexsBean.setPictureInfoList(list);
                            List<ReimbursementDetailEntity.AnnexsBean.DatabaseBean> list2 = new ArrayList<>();
                            annexsBean.setDatabase(list2);
                            reimbursementDetailEntity.getRepaymentAnnexs().add(annexsBean);
                        }
                        reimbursementList.addAll(reimbursementDetailEntity.getRepaymentAnnexs());
                        reimbursementAdapter.notifyDataSetChanged();
                        if (reimbursementList.size() > 0) {
                            reimbursementRcv.setVisibility(View.VISIBLE);
                        }
                    } else {
                        reimbursementDetailEntity.getAnnexs().clear();
                        filesList.clear();
                        for (int i = 0; i < data.getAnnexs().size(); i++) {
                            ReimbursementDetailEntity.AnnexsBean annexsBean = new ReimbursementDetailEntity.AnnexsBean();
                            annexsBean.setAnnexName(data.getAnnexs().get(i).getAnnexName());
                            annexsBean.setBaoixaoTypeCode(reimbursementTypeCode);
                            annexsBean.setNeedCd(data.getAnnexs().get(i).getNeedCd());
                            List<ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean> list = new ArrayList<>();
                            annexsBean.setPictureInfoList(list);
                            List<ReimbursementDetailEntity.AnnexsBean.DatabaseBean> list2 = new ArrayList<>();
                            annexsBean.setDatabase(list2);
                            reimbursementDetailEntity.getAnnexs().add(annexsBean);
                        }
                        filesList.addAll(reimbursementDetailEntity.getAnnexs());
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void selectDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", baoxiaoCode);
        map.put("type", type + "");//3补卡 4请假5外勤6图文7报销8物品9借款10补贴
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                if (data != null) {
                    if (tvType == null) {
                        return;
                    }
                    groupCode = data.getGroupCode();
                    groupName = data.getGroupName();
                    reimbursementTypeCode = data.getBaoixaoTypeCode();
                    baoxiaoTypeName = data.getBaoxiaoTypeName();
                    if (!Utils.isNull(data.getOrgName())) {
                        tvDepartment.setText(data.getOrgName());
                        orgCode = data.getOrgCode();
                        orgName = data.getOrgName();
                    }
                    if(!Utils.isNull(data.getGoodsCode())){
                        tvBorrow.setText("借款编号("+data.getGoodsCode()+")");
                    }
                    edMoney.setText(ClearMoreZeroUtil.subZeroAndDot(data.getAmt()));
                    if (reimbursement || isEditReimbursement) {
                        //还款
                        remark = data.getRemark();
                        tvCode.setText(data.getBaoxiaoCode());
                    } else {
                        tvType.setText(data.getBaoxiaoTypeName());
                        if (!Utils.isNull(data.getGroupCode())) {
                            tvGroup.setText(data.getGroupName() + "(" + ClockInUtils.getGroupEnd(data.getGroupCode()) + ")");
                            groupEmpty.setVisibility(View.VISIBLE);
                            llGroup.setVisibility(View.VISIBLE);
                        }
                        if (Utils.isNull(data.getRemark())) {
                            edContent.setText("无");
                        } else {
                            edContent.setText(data.getRemark());
                        }
                    }
                    filesList.clear();
                    filesList.addAll(data.getAnnexs());
                    adapter.notifyDataSetChanged();
                    if (reimbursement || isEditReimbursement) {
                        reimbursementList.clear();
                        reimbursementList.addAll(data.getRepaymentAnnexs());
                        reimbursementAdapter.notifyDataSetChanged();
                    }
                    if (reimbursement && type == 9) {
                        //获取还款附件名称
                        getReimbursementTypeList();
                        getReimbursementNameList(false);
                    } else {
                        getReimbursementNameList(true);
                    }

                    if (isEditReimbursement) {
                        //修改还款
                        threeList.clear();
                        shopList.clear();
                        shopList.addAll(data.getGoodsInfos());
                        if (shopList.size() == 0) {
                            shopRcv.setVisibility(View.GONE);
                        } else {
                            if (shopList.size() > 3) {
                                tvShopInit.setVisibility(View.VISIBLE);
                                threeList.addAll(shopList.subList(0, 3));
                            } else {
                                tvShopInit.setVisibility(View.GONE);
                                threeList.addAll(shopList);
                            }
                            emptyShop.setVisibility(View.VISIBLE);
                            llShop.setVisibility(View.VISIBLE);
                            shopRcv.setVisibility(View.VISIBLE);
                            shopChoiceAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getworkList();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
    }

    private void getworkList() {
        Map<String, String> map = new HashMap<>();
        //待审核 传0 已审核不传
        map.put("auditStatus", "0");
        map.put("pageNum", "1");
        map.put("pageSize", "1");
        // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销8物品9借款10补贴
        map.put("type", type + "");

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectKqMyWorkList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (ivAudit == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    ivAudit.setVisibility(View.VISIBLE);
                } else {
                    ivAudit.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                if (ivAudit != null) {
                    ivAudit.setVisibility(View.GONE);
                }
            }
        });
    }

    private void requestCamera(int type, int fileNum) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 0) {
                                //选图片
                                PictureSelector.create(ReimbursementActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9 - fileNum)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                //选文档
                                FilePicker
                                        .from(ReimbursementActivity.this)
                                        .chooseForMimeType()
                                        .setMaxCount(9 - fileNum)
                                        .setFileTypes("pdf", "doc", "ppt", "xls")
                                        .requestCode(REQUEST_CODE_CHOOSE)
                                        .start();
                            }

                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(ReimbursementActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                if (tvType == null) {
                    return;
                }
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    if (parentNum >= 0) {
                        ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean pictureInfoListBean = new ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean();
                        pictureInfoListBean.setPictureUrl(url);
                        pictureInfoListBean.setLocPictureUrl(url);
                        pictureInfoListBean.setBaoixaoTypeCode(reimbursementTypeCode);
                        if (reimbursement || isEditReimbursement) {
                            //还款
                            pictureInfoListBean.setAnnexName(reimbursementList.get(parentNum).getAnnexName());
                            reimbursementList.get(parentNum).getPictureInfoList().add(pictureInfoListBean);
                        } else {
                            pictureInfoListBean.setAnnexName(filesList.get(parentNum).getAnnexName());
                            filesList.get(parentNum).getPictureInfoList().add(pictureInfoListBean);
                        }

                    }
                }
                if (reimbursement || isEditReimbursement) {
                    //还款
                    if (reimbursementList.get(parentNum).getPictureInfoList().size() > 0) {
                        reimbursementAdapter.notifyItemChanged(parentNum);
                    }
                } else {
                    if (filesList.get(parentNum).getPictureInfoList().size() > 0) {
                        adapter.notifyItemChanged(parentNum);
                    }
                }


            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        ReimbursementDetailEntity.AnnexsBean.DatabaseBean docunmentEntity = new ReimbursementDetailEntity.AnnexsBean.DatabaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setDataCode("");
                        docunmentEntity.setDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setUploadTime(FileUtils.getDateTime(essFileList.get(i).getAbsolutePath()));
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        docunmentEntity.setBaoixaoTypeCode(reimbursementTypeCode);

                        if (reimbursement || isEditReimbursement) {
                            //还款
                            docunmentEntity.setAnnexName(reimbursementList.get(parentNum).getAnnexName());
                            reimbursementList.get(parentNum).getDatabase().add(docunmentEntity);
                        } else {
                            docunmentEntity.setAnnexName(filesList.get(parentNum).getAnnexName());
                            filesList.get(parentNum).getDatabase().add(docunmentEntity);
                        }

                        KLog.i(essFileList.get(i).getAbsolutePath());

                    }

                } else {
                    KLog.i("essFileList.size() == 0");
                }
                if (reimbursement || isEditReimbursement) {
                    //还款
                    if (reimbursementList.get(parentNum).getDatabase().size() > 0) {
                        reimbursementAdapter.notifyItemChanged(parentNum);
                    }
                } else {
                    if (filesList.get(parentNum).getDatabase().size() > 0) {
                        adapter.notifyItemChanged(parentNum);
                    }
                }

            }
        }
        if (requestCode == 1000) {
            if (data == null) {
                return;
            }

            borrow_index = data.getIntExtra("index", -1);
            if (borrow_index == -1) {
                borrowEntity = null;
                edMoney.setText("");
                tvBorrow.setText("");
                edMoney.setFocusableInTouchMode(true);
                edMoney.setFocusable(true);
                edMoney.requestFocus();
            } else {
                borrowEntity = (WorkNewEntity) data.getSerializableExtra("data");
                edMoney.setText(ClearMoreZeroUtil.subZeroAndDot(borrowEntity.getAmt()));
                tvBorrow.setText("借款编号(" +borrowEntity.getProjectCode() + ")");
                edMoney.setFocusable(false);
                edMoney.setFocusableInTouchMode(false);
            }

        }

    }

    private void uploadData() {
        Intent intent = new Intent(this, UploadReimbursementService.class);
        reimbursementDetailEntity.setProjectName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + "的" + tvType.getText().toString() + "报销申请");
        if (type == 7) {
            reimbursementDetailEntity.setType("1");//(1-报销 2-借款 3物品
            reimbursementDetailEntity.setRemark(edContent.getText().toString());
            if(borrowEntity!=null){
                reimbursementDetailEntity.setGoodsCode(borrowEntity.getProjectCode());
            }
        } else if (type == 10) {
            reimbursementDetailEntity.setType("5");//(1-报销 2-借款 3物品5补贴
            reimbursementDetailEntity.setRemark(edContent.getText().toString());
        } else {
            if (reimbursement) {
                reimbursementDetailEntity.setType("3");//
                reimbursementDetailEntity.setRemark(remark);
                reimbursementDetailEntity.setRepaymentRemark(edContent.getText().toString());
            } else if (isEditReimbursement) {
                reimbursementDetailEntity.setType("4");//
                reimbursementDetailEntity.setRemark(remark);
                reimbursementDetailEntity.setRepaymentRemark(edContent.getText().toString());
            } else {
                reimbursementDetailEntity.setType("2");//(1-报销 2-借款 3物品
                reimbursementDetailEntity.setRemark(edContent.getText().toString());
            }
            if (reimbursement || isEditReimbursement) {
                for (int i = 0; i < shopList.size(); i++) {
                    if (Utils.isNull(goodsCode)) {
                        goodsCode = goodsCode + shopList.get(i).getGoodsCode();
                    } else {
                        goodsCode = goodsCode + "," + shopList.get(i).getGoodsCode();
                    }
                }
                reimbursementDetailEntity.setGoodsCodes(goodsCode);
            }
        }
        reimbursementDetailEntity.setGroupCode(groupCode);
        reimbursementDetailEntity.setGroupName(groupName);
        reimbursementDetailEntity.setOrgCode(orgCode);
        reimbursementDetailEntity.setOrgName(orgName);
        reimbursementDetailEntity.setBaoixaoTypeCode(reimbursementTypeCode);
        if (!Utils.isNull(tvType.getText().toString())) {
            reimbursementDetailEntity.setBaoxiaoTypeName(tvType.getText().toString());
        } else {
            reimbursementDetailEntity.setBaoxiaoTypeName(baoxiaoTypeName);
        }

        reimbursementDetailEntity.setAmt(edMoney.getText().toString());
        reimbursementDetailEntity.setBaoxiaoCode(baoxiaoCode);
        reimbursementDetailEntity.setWorkflowId(workflowId);
        reimbursementDetailEntity.setCreateTime(Utils.getCurrentTime2());
        reimbursementDetailEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        reimbursementDetailEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        reimbursementDetailEntity.setCache(System.currentTimeMillis() + "");
        reimbursementDetailEntity.setCacheStatus(0);
        reimbursementDetailEntity.getAnnexs().clear();
        reimbursementDetailEntity.getAnnexs().addAll(filesList);
        reimbursementDetailEntity.getRepaymentAnnexs().clear();
        reimbursementDetailEntity.getRepaymentAnnexs().addAll(reimbursementList);
        intent.putExtra("reimbursementDetailEntity", reimbursementDetailEntity);
        intent.putExtra("cacheStatus", 0);
        startService(intent);
        finish();
    }

    private void uploadNoFile() {
        Map<String, Object> map = new HashMap<>();
        map.put("amt", edMoney.getText().toString());
        map.put("orgCode", orgCode);
        map.put("orgName", orgName);
        if (type == 7) {
            map.put("type", "1");//(1-报销 2-借款 3物品
            if(borrowEntity!=null){
                map.put("goodsCode", borrowEntity.getProjectCode());
            }
        } else if (type == 10) {
            map.put("type", "5");//(1-报销 2-借款 3物品
        } else {
            map.put("type", "2");//(1-报销 2-借款 3物品
        }
        map.put("baoixaoTypeCode", reimbursementTypeCode);
        if (!Utils.isNull(tvType.getText().toString())) {
            map.put("baoxiaoTypeName", tvType.getText().toString());
        } else {
            map.put("baoxiaoTypeName", baoxiaoTypeName);
            map.put("baoixaoTypeName", baoxiaoTypeName);
        }
        if (!Utils.isNull(groupCode)) {
            map.put("groupCode", groupCode);
            map.put("groupName", tvGroup.getText().toString());
        }
        map.put("remark", edContent.getText().toString());
        String url = "";
        if (Utils.isNull(baoxiaoCode)) {
            url = Urls.insertEmpBaoxiao;
        } else {
            url = Urls.updateEmpBaoxiao;
            map.put("baoxiaoCode", baoxiaoCode);
            map.put("workflowId", workflowId);
        }
        showLoading();
        MyHttpRequest.postRequestJson(url, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }

            }
        });
    }

    private void editReimbursement() {
        for (int i = 0; i < shopList.size(); i++) {
            if (Utils.isNull(goodsCode)) {
                goodsCode = goodsCode + shopList.get(i).getGoodsCode();
            } else {
                goodsCode = goodsCode + "," + shopList.get(i).getGoodsCode();
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("amt", edMoney.getText().toString());
        map.put("orgCode", orgCode);
        map.put("orgName", orgName);
        map.put("type", "2");//(1-报销 2-借款 3物品
        map.put("baoixaoTypeCode", reimbursementTypeCode);
        if (!Utils.isNull(tvType.getText().toString())) {
            map.put("baoxiaoTypeName", tvType.getText().toString());
        } else {
            map.put("baoxiaoTypeName", baoxiaoTypeName);
            map.put("baoixaoTypeName", baoxiaoTypeName);
        }
        if (!Utils.isNull(groupCode)) {
            map.put("groupCode", groupCode);
            if (!Utils.isNull(tvGroup.getText().toString())) {
                map.put("groupName", tvGroup.getText().toString());
            } else {
                map.put("groupName", groupName);
            }
        }
        map.put("repaymentRemark", edContent.getText().toString());
        map.put("repaymentCd", "1");
        map.put("baoxiaoCode", baoxiaoCode);
        map.put("workflowId", workflowId);
        map.put("goodsCode", goodsCode);
        showLoading();
        MyHttpRequest.postRequestJson(Urls.updateEmpBaoxiao, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }

            }
        });
    }

    private void uploadReimbursement() {
        for (int i = 0; i < shopList.size(); i++) {
            if (Utils.isNull(goodsCode)) {
                goodsCode = goodsCode + shopList.get(i).getGoodsCode();
            } else {
                goodsCode = goodsCode + "," + shopList.get(i).getGoodsCode();
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("amt", edMoney.getText().toString());
        map.put("orgCode", orgCode);
        map.put("orgName", orgName);
        map.put("repaymentCd", "1");
        map.put("baoixaoTypeCode", reimbursementTypeCode);
        map.put("baoxiaoTypeName", baoxiaoTypeName);
        map.put("groupCode", groupCode);
        map.put("groupName", groupName);
        map.put("remark", remark);
        map.put("repaymentRemark", edContent.getText().toString());
        map.put("baoxiaoCode", baoxiaoCode);
        map.put("workflowId", workflowId);
        map.put("goodsCode", goodsCode);
        showLoading();
        MyHttpRequest.postRequestJson(Urls.repayment, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject reObject = new JSONObject(response.body().toString());
                    if ("200".equals(reObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    int fileNum = 0;
    int parentNum = -1;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("Files_choice_parent_num")) {
                parentNum = Utils.changeNumber(map.get("Files_choice_parent_num"));
                int allNum = 0;
                if (reimbursement || isEditReimbursement) {
                    //还款
                    try {
                        fileNum = reimbursementList.get(parentNum).getPictureInfoList().size() + reimbursementList.get(parentNum).getDatabase().size();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    allNum = reimbursementList.size();
                } else {
                    try {
                        fileNum = filesList.get(parentNum).getPictureInfoList().size() + filesList.get(parentNum).getDatabase().size();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    allNum = filesList.size();
                }
                if (fileNum >= 9) {
                    MyToast.show("附件最多上传9个");
                    return;
                }
                if (allNum > parentNum) {
                    if (bottomDialog != null) {
                        bottomDialog.dismiss();
                    }
                    bottomDialog = new LogBottomDialog(this, false, new HomeBottomDialogListener() {
                        @Override
                        public void onListItemClick(int position) {
                            if (position == 0) {
                                requestCamera(0, fileNum);
                            } else if (position == 2) {
                                requestCamera(2, fileNum);
                            }
                        }
                    });
                    bottomDialog.show();
                }

            } else if (map.containsKey("deleteReimbursementPic")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    if (reimbursement || isEditReimbursement) {
                        //还款
                        FileUtilss.delFile(reimbursementList.get(parent_position).getPictureInfoList().get(position).getLocPictureUrl());
                        reimbursementList.get(parent_position).getPictureInfoList().remove(position);
                        reimbursementAdapter.notifyItemChanged(parent_position);
                    } else {
                        FileUtilss.delFile(filesList.get(parent_position).getPictureInfoList().get(position).getLocPictureUrl());
                        filesList.get(parent_position).getPictureInfoList().remove(position);
                        adapter.notifyItemChanged(parent_position);
                    }

                }
            }
            if (map.containsKey("deleteReimbursementDocunment")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    if (reimbursement || isEditReimbursement) {
                        //还款
                        reimbursementList.get(parent_position).getDatabase().remove(position);
                        reimbursementAdapter.notifyItemChanged(parent_position);
                    } else {
                        filesList.get(parent_position).getDatabase().remove(position);
                        adapter.notifyItemChanged(parent_position);
                    }

                }
            }
            if (map.containsKey("deleteShopPosition")) {
                int position = Utils.changeNumber(map.get("deleteShopPosition"));
                if (position >= 0) {
                    shopList.remove(position);
                    if (position <= 2) {
                        threeList.remove(position);
                        shopChoiceAdapter.notifyItemRemoved(position);
                        shopChoiceAdapter.notifyItemRangeChanged(position, shopList.size() - position);
                    }
                }
            }
            if (map.containsKey("select_baoixaoTypeCode")) {
                MyApp.fileEntity = null;
                reimbursementTypeCode = map.get("select_baoixaoTypeCode");
                tvType.setText(map.get("select_baoixaoTypeName"));
                if(Utils.isNull(map.get("select_baoixaoTypeRemark"))){
                    tvTypeRemark.setVisibility(View.GONE);
                }else{
                    tvTypeRemark.setText(map.get("select_baoixaoTypeRemark"));
                    tvTypeRemark.setVisibility(View.VISIBLE);
                }

                getReimbursementNameList(false);
                groupCode = "";
                groupName = "";
                tvGroup.setText("");
                groupEmpty.setVisibility(View.VISIBLE);
                llGroup.setVisibility(View.VISIBLE);
            }
        } else {
            String msg = messageEvent.getMessage();
            if (msg.equals("deleteShopClear")) {
                threeList.clear();
                shopList.clear();
                tvShopInit.setVisibility(View.GONE);
                shopRcv.setVisibility(View.GONE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(ShopEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getList() != null) {
            threeList.clear();
            shopList.clear();
            shopList.addAll(messageEvent.getList());
            if (shopList.size() > 3) {
                tvShopInit.setVisibility(View.VISIBLE);
                threeList.addAll(shopList.subList(0, 3));
            } else {
                tvShopInit.setVisibility(View.GONE);
                threeList.addAll(shopList);
            }
            if (shopList.size() == 0) {
                shopRcv.setVisibility(View.GONE);
            } else {
                shopRcv.setVisibility(View.VISIBLE);
                shopChoiceAdapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.llBorrow, R.id.ll_record, R.id.ll_audit, R.id.tvType, R.id.tvGroup, R.id.tvSure, R.id.llShopChoice})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.ll_record:
                intent = new Intent(this, MyAuditRecordActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.ll_audit:
                //审核
                intent = new Intent(this, AuditActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.llBorrow:
                //选择借款
                intent = new Intent(this, BorrowChoiceActivity.class);
                intent.putExtra("index", borrow_index);
                startActivityForResult(intent, 1000);
                break;
            case R.id.tvType:
                String typeDialogTitle = "";
                if (type == 7) {
                    intent = new Intent(this, ReimbursementTypesActivity.class);
                    startActivity(intent);
                    return;
                } else if (type == 10) {
                    typeDialogTitle = "补贴类型";
                } else {
                    typeDialogTitle = "借款类型";
                }
                if (reimbursementArray == null || reimbursementTypeEntities.size() == 0) {
                    MyToast.show(typeDialogTitle + "为空，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ReimbursementActivity.this)
                        .maxWidth(Utils.dip2px(ReimbursementActivity.this, 260))
                        .maxHeight(Utils.dip2px(ReimbursementActivity.this, 300))
                        .asCenterList("请选择" + typeDialogTitle, reimbursementArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        reimbursementTypeCode = reimbursementTypeEntities.get(position).getBaoixaoTypeCode();
                                        tvType.setText(text);
                                        getReimbursementNameList(false);
                                        if ("1".equals(reimbursementTypeEntities.get(position).getNeedGroupCd())) {
                                            groupCode = "";
                                            groupName = "";
                                            tvGroup.setText("");
                                            groupEmpty.setVisibility(View.VISIBLE);
                                            llGroup.setVisibility(View.VISIBLE);
                                        } else {
                                            groupCode = "";
                                            groupName = "";
                                            groupEmpty.setVisibility(View.GONE);
                                            llGroup.setVisibility(View.GONE);
                                        }
                                    }
                                })
                        .show();
                break;
            case R.id.tvGroup:
                if (groupArray == null) {
                    MyToast.show("无可选项目组，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ReimbursementActivity.this)
                        .maxWidth(Utils.dip2px(ReimbursementActivity.this, 260))
                        .maxHeight(Utils.dip2px(ReimbursementActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        groupName = groupEntities.get(position).getGroupName();
                                        tvGroup.setText(text.replace("[常驻]", "") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (reimbursement || isEditReimbursement) {
                    //还款  或者还款修改
                    if (Utils.isNull(edContent.getText().toString())) {
                        MyToast.show("请输入还款说明");
                        return;
                    }
                    int allSize = 0;
                    for (int i = 0; i < reimbursementList.size(); i++) {
                        int fileSize = reimbursementList.get(i).getDatabase().size() + reimbursementList.get(i).getPictureInfoList().size();
                        allSize = allSize + fileSize;
                        if (reimbursementList.get(i).getNeedCd().equals("1")) {
                            //1必传
                            if (fileSize == 0) {
                                MyToast.show("请选择" + reimbursementList.get(i).getAnnexName() + "必须的附件");
                                return;
                            }
                        }
                    }
                    if (allSize == 0) {
                        if (isEditReimbursement) {
                            editReimbursement();
                        } else {
                            uploadReimbursement();
                        }
                    } else {
                        uploadData();
                    }
                } else {
                    if (Utils.isNull(tvType.getText().toString())) {
                        if (type == 7) {
                            MyToast.show("请选择报销类型");
                        } else if (type == 10) {
                            MyToast.show("请选择补贴类型");
                        } else {
                            MyToast.show("请选择借款类型");
                        }
                        return;
                    }
                    if (llGroup.getVisibility() == View.VISIBLE) {
                        if (Utils.isNull(tvGroup.getText().toString())) {
                            MyToast.show("请选择项目组");
                            return;
                        }
                    }
                    if (Utils.isNull(edMoney.getText().toString())) {
                        if (type == 7) {
                            MyToast.show("请输入报销金额");
                        } else if (type == 10) {
                            MyToast.show("请输入补贴金额");
                        } else {
                            MyToast.show("请输入借款金额");
                        }
                        return;
                    }
                    if (Utils.isNull(edContent.getText().toString())) {
                        if (type == 7) {
                            MyToast.show("请输入报销事由");
                        } else if (type == 10) {
                            MyToast.show("请输入补贴事由");
                        } else {
                            MyToast.show("请输入借款事由");
                        }
                        return;
                    }
                    int allSize = 0;
                    for (int i = 0; i < filesList.size(); i++) {
                        int fileSize = filesList.get(i).getDatabase().size() + filesList.get(i).getPictureInfoList().size();
                        allSize = allSize + fileSize;
                        if (filesList.get(i).getNeedCd().equals("1")) {
                            //1必传
                            if (fileSize == 0) {
                                MyToast.show("请选择" + filesList.get(i).getAnnexName() + "必须的附件");
                                return;
                            }
                        }
                    }
                    if (allSize == 0) {
                        uploadNoFile();
                    } else {
                        uploadData();
                    }
                }
                break;
            case R.id.llShopChoice:
                //选择物品
                if (shopList.size() > 0) {
                    intent = new Intent(this, ShopChoiceActivity.class);
                    intent.putExtra("data", (Serializable) shopList);
                } else {
                    intent = new Intent(this, ShopNormalActivity.class);
                    intent.putExtra("data", (Serializable) shopList);
                }

                startActivity(intent);
                break;
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction() != null) {
                String action = intent.getAction();
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                if (action.equals(tag)) {
                    if (encryptStatus) {
                        for (int i = 0; i < filesList.size(); i++) {
                            for (int j = 0; j < filesList.get(i).getDatabase().size(); j++) {
                                if (filesList.get(i).getDatabase().get(j).getDataCode().equals(recevierDataCode)) {
                                    if (!filesList.get(i).getDatabase().get(j).isOpen()) {
                                        if (encryptStatus) {
                                            filesList.get(i).getDatabase().get(j).setOpen(true);
                                        }
                                        dealData(0, 0, 0, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                    }

                                }
                            }
                        }
                    } else {
                        int parent = 0;
                        int child = 0;
                        String datas = position + "";
                        if (datas.length() > 1) {
                            parent = Utils.changeNumber(datas.substring(0, 1));
                            child = Utils.changeNumber(datas.substring(1, 2));
                        }
                        for (int i = 0; i < filesList.get(parent).getDatabase().size(); i++) {
                            if (filesList.get(parent).getDatabase().get(i).getDataCode().equals(recevierDataCode)) {
                                if (!filesList.get(parent).getDatabase().get(i).isOpen()) {
                                    if (encryptStatus) {
                                        filesList.get(parent).getDatabase().get(i).setOpen(true);
                                    }
                                    dealData(0, parent, child, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                }

                            }
                        }
                    }
                } else {
                    if (encryptStatus) {
                        for (int i = 0; i < reimbursementList.size(); i++) {
                            for (int j = 0; j < reimbursementList.get(i).getDatabase().size(); j++) {
                                if (reimbursementList.get(i).getDatabase().get(j).getDataCode().equals(recevierDataCode)) {
                                    if (!reimbursementList.get(i).getDatabase().get(j).isOpen()) {
                                        if (encryptStatus) {
                                            reimbursementList.get(i).getDatabase().get(j).setOpen(true);
                                        }
                                        dealData(1, 0, 0, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                    }

                                }
                            }
                        }
                    } else {
                        int parent = 0;
                        int child = 0;
                        String datas = position + "";
                        if (datas.length() > 1) {
                            parent = Utils.changeNumber(datas.substring(0, 1));
                            child = Utils.changeNumber(datas.substring(1, 2));
                        }
                        for (int i = 0; i < reimbursementList.get(parent).getDatabase().size(); i++) {
                            if (reimbursementList.get(parent).getDatabase().get(i).getDataCode().equals(recevierDataCode)) {
                                if (!reimbursementList.get(parent).getDatabase().get(i).isOpen()) {
                                    if (encryptStatus) {
                                        reimbursementList.get(parent).getDatabase().get(i).setOpen(true);
                                    }
                                    dealData(1, parent, child, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                }

                            }
                        }
                    }
                }

            }
        }

    };

    /**
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     * @param type             0普通报销借款附件  1是还款附件
     */
    private void dealData(int type, int parent, int child, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (type == 0) {
                    if (adapter != null) {
                        filesList.get(parent).getDatabase().get(child).setProgress(percent);
                        adapter.setRefresh(child);
                    }
                } else {
                    if (reimbursementAdapter != null) {
                        reimbursementList.get(parent).getDatabase().get(child).setProgress(percent);
                        reimbursementAdapter.setRefresh(child);
                    }
                }
            } else if (percent == 100) {
                if (type == 0) {
                    if (adapter != null) {
                        filesList.get(parent).getDatabase().get(child).setProgress(100);
                        adapter.setRefresh(child);
                        new Thread() {
                            @Override
                            public void run() {
                                AESEncrypt.encryptFile(ReimbursementActivity.this, fileUrl, fileName, recevierDataCode, tag);
                            }
                        }.start();
                    }
                } else {
                    if (reimbursementAdapter != null) {
                        reimbursementList.get(parent).getDatabase().get(child).setProgress(100);
                        reimbursementAdapter.setRefresh(child);
                        new Thread() {
                            @Override
                            public void run() {
                                AESEncrypt.encryptFile(ReimbursementActivity.this, fileUrl, fileName, recevierDataCode, reimbursementTag);
                            }
                        }.start();
                    }
                }

            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        myIntentFilter.addAction(reimbursementTag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }
}
